package com.seguriapp.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

/**
 * Servlet that handles file downloads
 * 
 * @author Tania Gonzales (taniadgv@gmail.com)
 */
public class DownloadFileServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  private static final Logger LOGGER = Logger.getLogger(DownloadFileServlet.class);
  private static final String FILES_DIR_PATH = "/usuarios/seguriapp/uploaded/%ss/%s";
//  private static final String FILES_DIR_PATH = "C:\\test\\%ss\\%s";

  @Override
  protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    super.doGet(req, resp);
  }

  @Override
  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    LOGGER.info("Donwload File : ");
    final String fileName = new String(Base64.decodeBase64(req.getParameter("fileName").getBytes()));
    final String fileType = req.getParameter("fileType");

    LOGGER.info(fileType + " - " + fileName);
    resp.setContentType("APPLICATION/DOWNLOAD");
    resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    final OutputStream out = resp.getOutputStream();

    final FileInputStream fIn = new FileInputStream(String.format(FILES_DIR_PATH, fileType, fileName));
    LOGGER.info(" fIn " + fIn);
    final byte[] buffer = new byte[4096];
    int length;
    while ((length = fIn.read(buffer)) > 0) {
      out.write(buffer, 0, length);
    }
    fIn.close();
    out.flush();
    out.close();
    LOGGER.info("End Donwload File");
  }
}
